<template>
  <div class="app-container legal-wrap">
    <dynamic-legal-create
      ref="dynamicLegal"
      v-model="legalParam"
      :hide-required-asterisk="false"
      :rules="rules"
      :default-list="defaultList"
      :constructions="comLegalConstruction"
      :flow-structure="processDetail"
      :last-template="lastTemplate"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate"
      @showPreviewDrawer="showPreviewDrawer"
      @showTemplateDrawer="showTemplateDrawer"
      @legalSwitchChange="legalSwitchChange"
    />
    <div class="module-box">
      <table-title title="关联订单" style="margin-bottom: 9px;margin-top: 16px;">
        <el-tooltip :open-delay="300" placement="top" effect="dark">
          <div slot="content" style="max-width: 180px; line-height: 1.5">{{ relatedOrderTip }}</div>
          <tipIcon is-diy style="margin-left: 8px"/>
        </el-tooltip>
        <div class="total-amount-price">
          <img :src="incomeAmountIcon" alt="">
          总含税金额：<span class="price">{{ totalAmount }}</span>
        </div>
        <div v-if="!showMobilePage" class="options-btn-group">
          <PlainCreateBtn @click="onOrderAdd">添加</PlainCreateBtn>
          <el-button size="small" class="option-btn" @click="onOrderRelevance">关联订单</el-button>
          <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
        </div>
      </table-title>
      <div v-if="showMobilePage" class="pt10">
        <PlainCreateBtn @click="onOrderAdd">添加</PlainCreateBtn>
        <el-button size="small" class="option-btn" @click="onOrderRelevance">关联订单</el-button>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
      </div>
      <dynamicEditTable
        ref="dynamicEditTableRef"
        v-model="orders"
        :list-setting="listSetting"
        :is-edit="true"
        :show-serial="false"
        :show-add-btn="false"
        :fixed="showMobilePage?false:'right'"
        :default-params="defaultOrderItem"
        :special-column="['exeType', 'contentSource']"
        :order-private-id="orderPrivateId"
        :disable-valid-keys="['exeType', 'contentSource']"
        is-fill
        show-selection
        style="margin-top: 16px !important"
        @onSelectChange="onSelectChange"
        @orderPrivateIdChange="orderPrivateIdChange"
      />
      <related-orders
        ref="relatedOrders"
        :visible.sync="showRelatedOrders"
        @confirmRelatedOrder="confirmRelatedOrder"
        @onBack="relatedDrawerHide"
      />
      <!-- 关联合同 -->
      <ContractRelevance ref="contractRelevanceRef" v-model="legalParam.contractList" style="margin-top: 24px" />
    </div>
    <audit-process
      ref="auditProcess"
      :default-aduitor-list="[proposer]"
      :old-audit-info="legalDetail.oldAduitInfo"
      v-model="legalParam.aduitInfo"
      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submitFun"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!legalId" type="info" size="small" class="back-btn empty-btn-style" @click="toBackStep">上一步</el-button>
        <el-button v-if="setSubmitStatus()" type="primary" size="small" class="submit-btn" @click="submit(true)">发起审批</el-button>
        <el-button v-if="setSaveDraftStatus()" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回列表</el-button>
      </div>
    </fixed-pagination>
    <ContractTemplate
      ref="contractTemplateRef"
      :contract-type="type"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate" />
    <ContractPreview
      ref="ContractPreviewRef"
      :file-data="lastTemplate"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      :show-footer="false"
      is-fill
      @setDownloadParams="downloadPreviewFile"/>
  </div>
</template>
<script>
import DynamicLegalCreate from '../module/dynamicLegalCreate';
import ContractRelevance from '../module/contractRelevance';
import AuditProcess from '@/components/Common/auditProcess';
import TableTitle from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import ContractTemplate from '@/components/legal/contractTemplate/index';
import ContractPreview from '@/components/legal/contractTemplate/contractPreview';
import Common from '../mixins/common';
import OperationRelatedOrders from '../mixins/operationRelatedOrders';
import { weMediaLegalConstruct as legalConstruction } from '../model/legalConstruction';
import { legalOrderSetting } from '../../module/orderSetting';
import { typeOneRules, typeTwoRules } from '../model/legalRules';
import relatedOrders from '@/components/legal/relatedOrders';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
export default {
  name: 'WeMediaLegal',
  components: {
    DynamicLegalCreate,
    AuditProcess,
    TableTitle,
    dynamicEditTable,
    ContractTemplate,
    ContractPreview,
    ContractRelevance,
    relatedOrders
  },
  mixins: [Common, OperationRelatedOrders],
  props: {
    legalDetail: {
      type: Object | String,
      default: () => null
    },
    type: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      incomeAmountIcon,
      legalOrderSetting,
      typeOneRules,
      typeTwoRules,
      legalParam: { // 最终需要上传到接口上的参数
        createInfo: {
          createrDepartment: '',
          creater: '',
          createrPost: '',
          createrId: '',
          createrDepartmentId: '',
          proposer: null,
          proposerId: '',
          proposerAvatar: '',
          departmentId: '',
          post: '--',
          flowCode: ''
        },
        contractInfo: {
          type: 2,
          name: '',
          tempSource: '',
          subject: '',
          oppCompany: '',
          upstreamSign: '',
          upstreamPay: '',
          payAdvance: '',
          propertyOwner: '',
          code: '',
          date: {
            type: 1,
            legalDate: '', // 提交的时候需要删除
            startTime: '',
            endTime: '',
            stagesYearType: '',
            settleAccountPeriod: '',
            pushTime: '', // 单次类才有
            payWay: '', // 单次类才有
            items: [{ payDate: '' }]
          },
          theme: '',
          content: '',
          describe: '',
          attachment: [],
          // contractCodes: [{ code: '' }],
          ourStamp: '',
          stampType: '',
          legalTemplate: '',
          rebates: '', // 销售折扣/返利
          receivableAmount: null,
          payableAmount: null
        },
        submitType: 2,
        aduitInfo: {
          countersignSet: 0,
          process: [],
          senders: []
        },
        contractList: [] // 关联合同列表
      },
      defaultOrderItem: {
        customizeState: true
      },
      orders: [{
        customizeState: true,
        orderPrivateId: 1
      }],
      orderPrivateId: 1,
      deleteDisable: true,
      curSelectedRows: [],
      defaultList: {
        'createInfo.proposer': []
      },
      showRelatedOrders: false,
      comLegalConstruction: [],
      isStampInRules: false
    };
  },
  computed: {
    totalAmount() {
      let total = 0;
      this.orders.forEach(el => {
        if (el.contractPrice) {
          total += Number(el.contractPrice);
        }
      });
      return total.toFixed(2);
    },
    /* comLegalConstruction() {
      return legalConstruction(this.legalConstructionArg);
    }, */
    rules() {
      let rulesTemp;
      const isEnableStamp = [
        { required: true, message: '请选择盖章类型', trigger: 'blur' }
      ];
      if (this.legalParam.contractInfo.date.type === 1) {
        rulesTemp = this.typeOneRules;
      } else if (this.legalParam.contractInfo.date.type === 2) {
        rulesTemp = this.typeTwoRules;
      }
      if (this.isStampInRules) {
        rulesTemp['contractInfo.isEnableStamp'] = isEnableStamp;
      }
      if (this.legalParam.contractInfo.type !== 1) {
        return rulesTemp;
      } else {
        if (rulesTemp && rulesTemp['contractInfo.date.stagesYearType']) {
          rulesTemp['contractInfo.date.stagesYearType'][0].required = false;
        }
        return rulesTemp;
      }
    },
    listSetting() {
      const setting = this.legalOrderSetting;
      const isProject = this.orders.some(i => {
        return i.orderType === 2;
      });
      if (this.legalParam.contractInfo.date.type === 1) {
        setting.forEach(item => {
          item.isRequired = false;
        });
      } else {
        setting.forEach(item => {
          item.isRequired = true;
          // 只要有项目订单，就不用判断执行账号、下单平台 必填项
          if (isProject && (item.keyword === 'exeAccount' || item.keyword === 'orderPlatform')) {
            item.isRequired = false;
          }
        });
      }
      return setting;
    },
    relatedOrderTip() {
      return '批量关联的订单仅获取填充当时关联的订单信息，不随订单信息更新而改变该列表的信息';
    }
  },
  created() {
    this.comLegalConstruction = JSON.parse(JSON.stringify(legalConstruction(this.legalConstructionArg)));
  },
  methods: {
    onOrderAdd() {
      this.$refs['dynamicEditTableRef'].addValue();
    },
    onOrderRelevance() {
      this.formatOrderToTable(this.orders);
      this.showRelatedOrders = true;
      this.$refs['relatedOrders'].init();
    },
    legalSwitchChange(e) {
      this.isStampInRules = e;
    },
    handleRowsDel() {
      this.$confirm('确认删除已选中的订单信息吗？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        let curRow;
        // eslint-disable-next-line no-cond-assign
        while (curRow = this.curSelectedRows.pop()) {
          for (let index = this.orders.length - 1; index >= 0; index--) {
            if (this.orders[index].orderPrivateId === curRow.orderPrivateId) {
              this.orders.splice(index, 1);
            }
          }
        }
      });
    },
    confirmRelatedOrder(data) {
      this.setOrders(data);
      this.showRelatedOrders = false;
    },
    onSelectChange(list) {
      this.curSelectedRows = list;
      this.deleteDisable = !list.length || !(list.length < this.orders.length);
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    relatedDrawerHide() {
      this.showRelatedOrders = false;
    },
    submitFun(senders = []) {
      this.modifySenders = senders;// 存到mixins
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isSubmit) return;
      const params = JSON.parse(JSON.stringify(this.legalParam));
      if (this.reapplyId) {
        params.submitType = 3;
        params.byReapplyId = this.legalId;
      } else {
        params.submitType = 2;
        if (params.hasOwnProperty('byReapplyId')) delete params.byReapplyId;
      }
      this.remodifyId && (params.byRemodifyId = this.remodifyId);
      params.orders = this.orderPriceSwitch(this.orders, 2);
      if (params.contractList && params.contractList.length) {
        params.contractList.forEach(it => {
          if (typeof it.proposerName === 'number') {
            it.proposer = it.proposerName;
          }
        });
      }
      delete params.createInfo.creater;
      delete params.createInfo.createrDepartment;
      delete params.createInfo.proposer;
      if (this.isSigner === 0) {
        params.aduitInfo = this.removeSigner(params.aduitInfo);
      }
      if (this.legalId && !this.createNew) {
        this.handleModifyData(params);
      }
      const message = (this.legalId && !this.createNew && !this.setSaveDraftStatus()) ? '合同修改成功' : '合同新建成功';
      this.handlePost(params, message);
    }
  }
};
</script>
<style lang="scss" scoped>
.legal-wrap {
  .footer-btn-wrap {
    display: flex;
    justify-content: center;
  }
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 12px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .module-box {
    // margin-bottom: 40px;
    padding-bottom: 32px;
    .options-btn-group {
      position: absolute;
      right: 0;
      .option-btn {
        margin-left: 8px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
::v-deep .el-form-item__error {
  padding-top: 2px !important;
}
.hover-icon {
  color: #999;
  &:hover {
    color: #406eff;
  }
}
 ::v-deep .dynamic-container {
  .el-table__row {
    .cell {
      .el-input__inner {
        height: 48px !important;
      }
    }
  }
}
</style>
